package com.example.luyennghe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class NgheActivity extends Activity {
    private UserInfo user = new UserInfo();
    private Bundle extras;
    private BaiNghe _bainghe;
    
    private ProgressDialog pDialog;
    private TextView tvNoiDungCauHoi;
    private RadioGroup rg;
    private RadioButton rad1;
    private RadioButton rad2;
    private RadioButton rad3;
    private RadioButton rad4;
    private Button btnTruoc;
    private Button btnSau;
    private Button btnNopbai;   
    private Button btnPlay;
    private Button btnPause;
    private Button btnStop;
    private SeekBar seekbar;
    private TextView tvBainghe;
    private TextView duration;
    private TextView playedTime;
    
    private MediaPlayer mediaPlayer;
    private int maxsoCauHoi = 10;
    private ArrayList<CauHoi> listCauHoi = new ArrayList<CauHoi>();
    private ArrayList<String> listDapAn = new ArrayList<String>(maxsoCauHoi);
    private ArrayList<String> cauTraLoi = new ArrayList<String>(maxsoCauHoi);
    private CauHoi cauhoi_temp;

    private int cauHoiHienTai, soCauHoi;
    private final Handler handler = new Handler();
    private Boolean isPlaying = false;
    private Boolean isStop = false;
    
    JSONParser jParser = new JSONParser();
    private static String urlDsCauHoi = "http://huynh.cu.cc/android-server/get_cauhoi.php";
    private static String urlDaLamBai = "http://huynh.cu.cc/android-server/dalambai.php";
    private String path;
    //JSON node
    private static final String TAG_STT = "stt";
    private static final String TAG_ID_BAINGHE = "id_bainghe";
    private static final String TAG_CAPDO = "capdo";
    private static final String TAG_FILEPATH = "filepath";
    
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_DSCAUHOI = "dscauhoi";
    private static final String TAG_STT_CAUHOI = "stt_cauhoi";
    private static final String TAG_NOIDUNGCAUHOI = "noidungcauhoi";
    private static final String TAG_A = "a";
    private static final String TAG_B = "b";
    private static final String TAG_C = "c";
    private static final String TAG_D = "d";
    private static final String TAG_DAPAN = "dapan";
    
    private static final String TAG_USERNAME = "username";
    private static final String TAG_BAINGHE = "bainghe";
    private static final String TAG_DIEM = "diem";
    private static final String TAG_NGAYLAM = "ngaylam";
    private boolean loadCauHoi_Success = false;
    private boolean loadCauHoi_Error = false;
    private boolean loadCauHoi_ErrorConnect = false;
    private boolean daLam_Success = false;
    private boolean daLam_ErrorConnect = false;
    private boolean daLam_ErrorInserted = false;
        
    JSONArray dsCauHoi = new JSONArray();
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nghe_activity_layout);
        tvNoiDungCauHoi = (TextView)findViewById(R.id.tvNoidungcauhoi);
        rg = (RadioGroup)findViewById(R.id.radGroup);
        rad1 = (RadioButton)findViewById(R.id.rad1);
        rad2 = (RadioButton)findViewById(R.id.rad2);
        rad3 = (RadioButton)findViewById(R.id.rad3);
        rad4 = (RadioButton)findViewById(R.id.rad4);
        btnTruoc = (Button)findViewById(R.id.btnTruoc);
        btnSau = (Button)findViewById(R.id.btnSau);
        btnNopbai = (Button)findViewById(R.id.btnNopbai);
        btnPlay = (Button)findViewById(R.id.btnPlay);
        btnPause = (Button)findViewById(R.id.btnPause);
        btnStop = (Button)findViewById(R.id.btnStop);
        seekbar = (SeekBar)findViewById(R.id.seekbar);
        tvBainghe = (TextView)findViewById(R.id.tvBainghe);   
        duration = (TextView)findViewById(R.id.duration);
        playedTime = (TextView)findViewById(R.id.playedtime);
        //get data...
        extras = getIntent().getExtras();
        if (extras != null) {
            path = extras.getString(TAG_FILEPATH);
            _bainghe = (BaiNghe)extras.getSerializable("bainghe");
            user = (UserInfo)extras.getSerializable("userinfo");
            Log.d("User", user.getUsername());
            Log.d("bainghe ", _bainghe.getId());
        }
        else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    NgheActivity.this);
            builder.setTitle("Lỗi")
                    .setMessage("Có lỗi xảy ra. Hãy thử lại sau.")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        soCauHoi = 0; 
        cauHoiHienTai = 0;
        tvBainghe.setText("Bài " + _bainghe.getStt() + ". " + _bainghe.getTenBainghe());
        //kiểm tra kết nối internet
        if (!checkInternetConnection()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    NgheActivity.this);
            builder.setTitle("Lỗi")
                    .setMessage("Không có kết nối internet. Hãy thử lại sau.")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    onBackPressed();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        
        //đặt giá trị mặc định cho list dapan và cauTraLoi
        for(int i=0; i<maxsoCauHoi; i++){
            listDapAn.add("y");
            cauTraLoi.add("x");
        }        
              
        try{
            loadMedia();
        }
        catch(Exception ex){
            Toast.makeText(NgheActivity.this, "Lỗi load media. Xin hãy thử lại.", Toast.LENGTH_SHORT).show();
            finish();
        }

        //tai cau hoi tu server
        loadCauHoiHandler();
        //sự kiện cho các button câu hỏi trước, sau, nộp bài
        btnTruoc.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                if(cauHoiHienTai==0){
                    return;
                }
                else
                {
                    cauHoiHienTai--;
                    hienThiCauHoi(cauHoiHienTai);                   
                }
            }
        });
        btnSau.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                if(cauHoiHienTai==soCauHoi-1){
                    return;
                }
                else
                {
                    cauHoiHienTai++;
                    hienThiCauHoi(cauHoiHienTai);
                }
            }
        });    
        btnNopbai.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                if(!hoanThanhBaiNghe())
                {       
                    AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                    builder.setTitle("Xác nhận")
                            .setMessage("Bạn chưa trả lời hết các câu hỏi. Bạn có chắc chắn muốn kết thúc bài làm?")
                            .setCancelable(false)
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("Có",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            tinhDiem();
                                            Log.d("Diem", _bainghe.getDiem());
                                            AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                                            builder.setTitle("Kết quả")
                                                   .setMessage("Bạn đã trả lời đúng " + _bainghe.getDiem() + "/" + String.valueOf(soCauHoi) + " câu hỏi.")
                                                   .setCancelable(false)
                                                   .setIcon(R.drawable.ok_icon)
                                                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                       public void onClick(DialogInterface dialog, int id) {
                                                           dialog.dismiss();
                                                           nopBaiHandler();
                                                       }
                                                   });
                                            AlertDialog alert = builder.create();
                                            alert.show();
                                        }
                                    })
                            .setNegativeButton("Không",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });                 

                    builder.create().show();
                }
                if(hoanThanhBaiNghe())
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                    builder.setTitle("Xác nhận")
                            .setMessage("Bạn có chắc chắn muốn kết thúc bài làm?")
                            .setCancelable(false)
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("Có",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {   
                                            tinhDiem();
                                            AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                                            builder.setTitle("Kết quả")
                                                   .setMessage("Bạn đã trả lời đúng " + _bainghe.getDiem() + "/" + String.valueOf(soCauHoi) + " câu hỏi.")
                                                   .setCancelable(false)
                                                   .setIcon(R.drawable.ok_icon)
                                                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                       public void onClick(DialogInterface dialog, int id) {
                                                           dialog.dismiss();
                                                           nopBaiHandler();
                                                       }
                                                   });
                                            AlertDialog alert = builder.create();
                                            alert.show();
                                        }
                                    })
                            .setNegativeButton("Không",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.cancel();
                                        }
                                    });                 

                    builder.create().show();
                }
            }
        });
        //radiogroup 
        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                switch (checkedId){
                case R.id.rad1:
                        cauTraLoi.set(cauHoiHienTai, "a");
                        break;
                case R.id.rad2:
                        cauTraLoi.set(cauHoiHienTai, "b");
                        break;
                case R.id.rad3:
                        cauTraLoi.set(cauHoiHienTai, "c");
                        break;
                case R.id.rad4:
                        cauTraLoi.set(cauHoiHienTai, "d");
                        break;
                default:
                    cauTraLoi.set(cauHoiHienTai, "x");
                }
            }
        });
        
    }
    class LoadCauHoi extends AsyncTask<String, String, String> {
         
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NgheActivity.this);
            pDialog.setMessage("Đang tải câu hỏi. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            loadCauHoiMethod();
            return "";
        }
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if(loadCauHoi_Success){
                loadCauHoi_Success = false;
                btnTruoc.setEnabled(true);
                btnSau.setEnabled(true);
                btnNopbai.setEnabled(true);
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        hienThiCauHoi(cauHoiHienTai);
                    }
                });
            } 
            else
                if(loadCauHoi_Error){
                    loadCauHoi_Error = false;
                    AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                    builder.setTitle("Lỗi")
                           .setIcon(R.drawable.warning_icon)
                           .setMessage("Không tìm thấy câu hỏi.")
                           .setCancelable(false)
                           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                               public void onClick(DialogInterface dialog, int id) {
                                   dialog.dismiss();
                                   onBackPressed();
                               }
                           });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
                else
                    if(loadCauHoi_ErrorConnect){
                        loadCauHoi_ErrorConnect = false;
                        AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
                        builder.setTitle("Lỗi")
                               .setIcon(R.drawable.warning_icon)
                               .setMessage("Không thể kết nối đến database. Vui lòng thử lại.")
                               .setCancelable(false)
                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       dialog.dismiss();
                                   }
                               });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                
        }
    }
    
    public void hienThiCauHoi(int cauhoi){
        try{
            cauhoi_temp = listCauHoi.get(cauhoi);           
            String noidung = cauhoi_temp.getCauHoi() + ". "+ cauhoi_temp.getNoiDung();
            tvNoiDungCauHoi.setText(noidung);       
            rad1.setText(cauhoi_temp.getA());
            rad2.setText(cauhoi_temp.getB());
            rad3.setText(cauhoi_temp.getC());
            rad4.setText(cauhoi_temp.getD());   
            String temp = cauTraLoi.get(cauhoi);
            
            //kiểm tra nếu người dùng đã chọn câu trả lời thì check vào phương án đã chọn
            if(temp!="x"){
                int n = 0;
                if(temp=="a") n=1;
                if(temp=="b") n=2;
                if(temp=="c") n=3;
                if(temp=="d") n=4;
                switch (n){
                case 1:
                        rg.check(R.id.rad1);
                        break;
                case 2:
                        rg.check(R.id.rad2);
                        break;
                case 3:
                        rg.check(R.id.rad3);
                        break;
                case 4:
                        rg.check(R.id.rad4);
                        break;
                default:
                        rg.clearCheck();
                }
            }
            else
                rg.clearCheck();
        }
        catch(Exception ex){
            AlertDialog.Builder builder = new AlertDialog.Builder(NgheActivity.this);
            builder.setMessage("Lỗi: Không thể hiển thị bài nghe... " + ex.getMessage())
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           onBackPressed();
                       }
                   });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }
    public void tinhDiem(){
        int temp = 0;
        for (int i = 0; i < listDapAn.size(); i++) {
            if (listDapAn.get(i).equalsIgnoreCase(cauTraLoi.get(i))) {
                temp++;
            }
        }
        _bainghe.setDiem(String.valueOf(temp));
    }
    public Boolean hoanThanhBaiNghe(){
        for(int i=0;i<soCauHoi;i++){
            if(cauTraLoi.get(i)=="x")
                return false;
        }
        return true;
    }
    
    // xử lý phần nghe...
    public void loadMedia() {
        mediaPlayer = new MediaPlayer();
        btnPlay.setOnClickListener(btnPlayListener);
        btnPause.setOnClickListener(btnPauseListener);
        btnStop.setOnClickListener(btnStopListener);
        btnPlay.setEnabled(true);
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            public void onCompletion(MediaPlayer mPlayer) {
                btnPlay.setEnabled(true);
                btnPause.setEnabled(false);
                btnStop.setEnabled(false);
                isStop = true;
                isPlaying = false;
            }

        });
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        }
        seekbar.setMax(mediaPlayer.getDuration());
        duration.setText("Thời lượng "+getTime(mediaPlayer.getDuration()));
        seekbar.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                seekChange(v);
                return false;
            }
        });
    }

    public void startPlayProgressUpdater() {
        seekbar.setProgress(mediaPlayer.getCurrentPosition());
        playedTime.setText(getTime(mediaPlayer.getCurrentPosition()));
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    startPlayProgressUpdater();
                }
            };
            handler.postDelayed(notification, 1000);
        } else {
            mediaPlayer.pause();
            // seekbar.setProgress(0);
        }
    }
    private String getTime(int milisecond){
        String minute, second;
        int min, sec, temp;
        temp = milisecond/1000;
        min = temp/60;
        sec = temp%60;
        if(min<10)
        {
            minute = "0" + String.valueOf(min);
        }
        else
            minute = String.valueOf(min);
        if(sec<10)
        {
            second = "0" + String.valueOf(sec);
        }
        else
            second = String.valueOf(sec);
        return minute+ " : " + second;
    }
    private void seekChange(View v) {
        // if(mediaPlayer.isPlaying()){
        SeekBar sb = (SeekBar) v;
        mediaPlayer.seekTo(sb.getProgress());
        playedTime.setText(getTime(mediaPlayer.getCurrentPosition()));      
        // }
    }

    Button.OnClickListener btnPlayListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (isPlaying == false) {
                isPlaying = true;
                if (isStop) {
                    loadMedia();
                    isStop = false;
                }
                mediaPlayer.start();
                startPlayProgressUpdater();
                btnPlay.setEnabled(false);
                btnPause.setEnabled(true);
                btnStop.setEnabled(true);
            }
        }
    };
    Button.OnClickListener btnPauseListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mediaPlayer.isPlaying() == true && isPlaying == true) {
                isPlaying = false;
                mediaPlayer.pause();
                btnPlay.setEnabled(true);
                btnPause.setEnabled(false);
                btnStop.setEnabled(true);   
            }           
        }
    };
    Button.OnClickListener btnStopListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            isPlaying = false;
            isStop = true;          
            mediaPlayer.reset();        
            seekbar.setProgress(0); 
            btnPlay.setEnabled(true);
            btnPause.setEnabled(false);
            btnStop.setEnabled(false);  
            loadMedia();
        }
    };

    // kiểm tra kết nối internet
    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // kiểm tra kết nối wifi và mobile(3G)
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        
        try{
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        catch(Exception ex){
            Toast.makeText(NgheActivity.this, "Lỗi media...", Toast.LENGTH_SHORT).show();
        }
        super.onBackPressed();
        finish();
    }
    
    @Override
    public void onStop() {
        try{
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }           
            super.onStop();
        }
        catch (Exception ex){
            
        }
    }
    @Override
    protected void onDestroy() {
        Log.d("tag :", "App destoryed");
        super.onDestroy();
    }
    class NopBaiClass extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();      
            pDialog = new ProgressDialog(NgheActivity.this);
            pDialog.setMessage("Đang kết nối đến server. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            nopBaiMethod();
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            pDialog.dismiss();
            if(daLam_Success){     
                daLam_Success = false;
                Toast.makeText(getApplicationContext(), "Đã lưu kết quả lên server.", Toast.LENGTH_SHORT).show();
            }
            else
                if(daLam_ErrorInserted ||daLam_ErrorConnect) 
                {
                    daLam_ErrorConnect = false;
                    daLam_ErrorInserted = false;
                    Toast.makeText(getApplicationContext(), "Không thể lưu kết quả lên server.", Toast.LENGTH_SHORT).show();
                }
                
        }
    }
    public void nopBaiHandler(){
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            btnPlay.setEnabled(false);
        }
        btnNopbai.setEnabled(false);
        btnStop.setEnabled(false);
        btnPause.setEnabled(false);
        rad1.setEnabled(false);
        rad2.setEnabled(false);
        rad3.setEnabled(false);
        rad4.setEnabled(false);
        final NopBaiClass _nopbai = new NopBaiClass();
        try {
            _nopbai.execute();
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (_nopbai.getStatus() == AsyncTask.Status.RUNNING) {
                        _nopbai.cancel(true);
                        pDialog.dismiss();
                        Toast.makeText(getApplicationContext(),
                                "Time out. Không thể lưu kết quả lên server. Xin hãy thử lại.",
                                Toast.LENGTH_SHORT).show();
                        btnNopbai.setEnabled(true);
                    }
                }
            }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối
                       // được.
        }
        catch (Exception ex){
            Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
        }
    }
    
    public void nopBaiMethod(){
     // Building Parameters            
        Calendar c1 = Calendar.getInstance();      
        String ngaylam = String.valueOf(c1.get(Calendar.HOUR_OF_DAY)) + ":" +String.valueOf(c1.get(Calendar.MINUTE)) + " - " +  String.valueOf(c1.get(Calendar.DAY_OF_MONTH))+ "/" + String.valueOf(c1.get(Calendar.MONTH)+1) +"/" + String.valueOf(c1.get(Calendar.YEAR));
        _bainghe.setNgayLam(ngaylam);
        List<NameValuePair> paramsNopbai = new ArrayList<NameValuePair>();
        paramsNopbai.add(new BasicNameValuePair(TAG_USERNAME, user.getUsername()));   
        paramsNopbai.add(new BasicNameValuePair(TAG_BAINGHE, _bainghe.getId()));
        paramsNopbai.add(new BasicNameValuePair(TAG_DIEM, _bainghe.getDiem()));
        paramsNopbai.add(new BasicNameValuePair(TAG_NGAYLAM, _bainghe.getNgayLam()));
        JSONObject json = new JSONObject();
        // getting JSON string from URL
        try {               
            //gui du lieu len server
            json = jParser.makeHttpRequest(urlDaLamBai, "POST",
                    paramsNopbai);
            Log.d("dalam: ", json.toString());
            Log.d("ngay lam: ", ngaylam);
            // Check SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            String mes = json.getString(TAG_MESSAGE);
            if (success == 1 && mes.equals("OK")) {
                daLam_Success = true;                   
            }
            else
            {
                if(success==0 && mes.equals("Can't insert into database")){
                    daLam_ErrorInserted = true;
                }
                else
                {
                    daLam_ErrorConnect = true;
                }
            }
                
        } 
        catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            onBackPressed();
        }
    }
    public void loadCauHoiHandler(){
        final LoadCauHoi loadCauHoi = new LoadCauHoi();
        try{            
            loadCauHoi.execute();        
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (loadCauHoi.getStatus() == AsyncTask.Status.RUNNING) {
                        loadCauHoi.cancel(true);
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                NgheActivity.this);
                        builder.setMessage(
                                "Kết nối quá thời gian. Xin hãy thử lại.")
                                .setCancelable(false)
                                .setTitle("Lỗi")
                                .setIcon(R.drawable.warning_icon)
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(
                                                    DialogInterface dialog, int id) {
                                                dialog.dismiss();
                                                onBackPressed();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
    
                }
            }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối được.
        }
        catch (Exception ex){
            Toast.makeText(NgheActivity.this, "Khong the tai cau hoi tu server", Toast.LENGTH_SHORT).show();
        }
    }
    public void loadCauHoiMethod(){
     // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_CAPDO, _bainghe.getCapDo()));
        params.add(new BasicNameValuePair(TAG_STT, _bainghe.getStt()));
        params.add(new BasicNameValuePair(TAG_ID_BAINGHE, _bainghe.getId()));
        // getting JSON string from URL
        try {
            JSONObject json = jParser.makeHttpRequest(urlDsCauHoi, "GET",
                    params);
            // Check your log cat for JSON reponse
            Log.d("DS câu hỏi: ", json.toString());
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    loadCauHoi_Success = true;
                    dsCauHoi = json.getJSONArray(TAG_DSCAUHOI);
                    for (int i = 0; i < dsCauHoi.length(); i++) {
                        JSONObject obj = dsCauHoi.getJSONObject(i);
                        String stt_cauhoi = obj.getString(TAG_STT_CAUHOI);
                        String noidungcauhoi = obj.getString(TAG_NOIDUNGCAUHOI);
                        String a = obj.getString(TAG_A);
                        String b = obj.getString(TAG_B);
                        String c = obj.getString(TAG_C);
                        String d = obj.getString(TAG_D);
                        String dapan = obj.getString(TAG_DAPAN);
                        cauhoi_temp = new CauHoi();
                        cauhoi_temp.setCapDo(_bainghe.getCapDo());
                        cauhoi_temp.setIdBainghe(_bainghe.getId());
                        cauhoi_temp.setCauHoi(stt_cauhoi);
                        cauhoi_temp.setSttBainghe(_bainghe.getStt());
                        cauhoi_temp.setNoiDung(noidungcauhoi);
                        cauhoi_temp.setA(a);
                        cauhoi_temp.setB(b);
                        cauhoi_temp.setC(c);
                        cauhoi_temp.setD(d);
                        cauhoi_temp.setDapAn(dapan);
                        listCauHoi.add(cauhoi_temp);
                        Log.d("Số câu hỏi ",
                                String.valueOf(listCauHoi.size()));
                        listDapAn.set(soCauHoi, dapan);
                        soCauHoi++;
                    }
                } 
                else 
                    if(success==0 && mes.equals("No question found"))
                        loadCauHoi_Error = true;
                    else
                        loadCauHoi_ErrorConnect = true;
        }
        catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), "Có lỗi xảy ra: " + ex.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}
